package easy;

/**
 * 14. 最长公共前缀
 * 创建时间：2024-03-19 11:41
 * 内容：编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀，返回空字符串 ""。
 * 地址：https://leetcode.cn/problems/longest-common-prefix/description/
 */
public class 最长公共前缀_14 {
    public static String longestCommonPrefix(String[] strs) {
        char[] chars = strs[0].toCharArray();
        int charsLen = chars.length;
        for (int i = 1; i < strs.length; i++) {
            char[] charArray = strs[i].toCharArray();
            charsLen = Math.min(charsLen, charArray.length);
            for (int j = 0; j < charsLen; j++) {
                if (chars[j] != charArray[j]) {
                    charsLen = j;
                    break;
                }
            }
            if (charsLen == 0) {
                break;
            }
        }
        return charsLen <= 0 ? "" : String.copyValueOf(chars, 0, charsLen);
    }

    public static void main(String[] args) {
        String[] a = {"ab","a"};
        System.out.println(longestCommonPrefix(a));
    }
}
